package logic

import (
	"context"
	"edu-pro/edurpc/edurpc"
	"edu-pro/pkg"
	"strconv"

	"edu-pro/api/internal/svc"
	"edu-pro/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginWithPwdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginWithPwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginWithPwdLogic {
	return &LoginWithPwdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginWithPwdLogic) LoginWithPwd(req *types.LoginWithPwdRequest) (resp *types.Response, err error) {
	// •	手机号 + 密码登录
	if len(req.Phone) != 11 {
		return &types.Response{
			Message: "请输入正确手机号",
			Code:    500,
			Data:    nil,
		}, nil
	}
	data, err := l.svcCtx.EduRpc.UserLoginWithPwd(l.ctx, &edurpc.UserLoginWithPwdRequest{
		Phone:    req.Phone,
		Password: req.Password,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	handler, err := pkg.TokenHandler(strconv.FormatInt(data.UserId, 10))
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "用户登录成功",
		Code:    200,
		Data:    handler,
	}, nil
}
